import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;
import 'package:flutter_app_1_25_0/testWidget/image/io_asset.dart'
    if (dart.library.io) 'package:flutter_app_1_25_0/testWidget/image/io_asset.dart'
    if (dart.library.html) 'package:flutter_app_1_25_0/testWidget/image/browser_asset.dart';
import 'package:websafe_svg/websafe_svg.dart';

enum ResourceType {
  unknown,
  asset,
  net,
  file,
}

/// 图片展示
/// @owner dansun
/// @groupInfo [ComponentGroupInfo.layout]
///
class ImageViewWidget extends StatelessWidget {
  @Deprecated('Use ImageViewWidget.asset ImageViewWidget.file ImageViewWidget.network')
  ImageViewWidget({
    @required this.imageUrl,
    Key key,
    this.placeHoldUrl,
    this.package,
    this.width,
    this.height,
    this.fit,
    this.placeHoldWidget,
    this.borderRadius,
    this.placeHoldPackage,
    this.color,
    this.loadingAnimation = false,
  })  : _resourceType = checkImageUrlIsNetwork(imageUrl)
            ? ResourceType.net
            : imageUrl.startsWith('assets') != null
                ? ResourceType.asset
                : ResourceType.unknown,
        super(key: key);

  ImageViewWidget.asset(
      {@required this.imageUrl,
      Key key,
      this.package,
      this.placeHoldUrl,
      this.placeHoldWidget,
      this.width,
      this.height,
      this.color,
      this.placeHoldPackage,
      this.borderRadius,
      this.fit,
      this.loadingAnimation = false})
      : _resourceType = ResourceType.asset,
        super(key: key);

  ImageViewWidget.file(
      {@required this.imageUrl,
      Key key,
      this.package,
      this.placeHoldUrl,
      this.placeHoldWidget,
      this.width,
      this.height,
      this.color,
      this.placeHoldPackage,
      this.borderRadius,
      this.fit,
      this.loadingAnimation = false})
      : _resourceType = ResourceType.file,
        super(key: key);

  ImageViewWidget.network(
      {@required this.imageUrl,
      Key key,
      this.package,
      this.placeHoldUrl,
      this.placeHoldWidget,
      this.placeHoldPackage,
      this.width,
      this.height,
      this.color,
      this.borderRadius,
      this.fit,
      this.loadingAnimation = false})
      : _resourceType = ResourceType.net,
        super(key: key);

  ///支持本地文件以及网络 svg 等图片记载
  final String imageUrl;

  ///资源所在package 本地资源
  final String package;

  ///占位图片
  final String placeHoldUrl;

  ///占位图片 package
  final String placeHoldPackage;

  ///占位widget 优先于placeHoldUrl 显示
  final Widget placeHoldWidget;

  ///图片大小
  final double width;
  final double height;

  final Color color;

  ///图片圆角
  final BorderRadius borderRadius;

  final BoxFit fit;

  ///加载动画
  final bool loadingAnimation;

  final ResourceType _resourceType;

  static bool checkImageUrlIsNetwork(String url) {
    if (url == null || url.isEmpty) {
      return false;
    }
    return url.startsWith('http://') || url.startsWith('https://') || url.startsWith('blob:http://') || url.startsWith('blob:https://');
  }

  bool isAssetResource(String url) {
    if (checkImageUrlIsNetwork(url)) {
      return false;
    }

    ///asset 资源给的地址是相对路径
    return !path.isRelative(url);
  }
  //
  // ///加载 file中的svg 资源
  // Future<Uint8List> _getSvgData(String imageUrl) async {
  //   File file = File(imageUrl);
  //   if (!file.existsSync()) {
  //     return null;
  //   }
  //   return file.readAsBytes();
  // }

  ///构建svg 图片
  Widget _buildSvgWidget() {
    if (_resourceType == ResourceType.file) {
      return svgFromFile(
        imageUrl: imageUrl,
        width: width,
        height: height,
        color: color,
        fit: fit,
        placeholderBuilder: (context) {
          return _placeHoldWidget();
        },
      );
    }

    ///网络资源
    if (_resourceType == ResourceType.net) {
      return WebsafeSvg.network(
        imageUrl,
        width: width,
        height: height,
        color: color,
        fit: fit ?? BoxFit.cover,
        placeholderBuilder: (context) {
          return _placeHoldWidget();
        },
      );
    }
    if (_resourceType == ResourceType.asset) {
      ///本地资源
      return svgFromAsset(
        imageUrl,
        width: width,
        height: height,
        color: color,
        fit: fit ?? BoxFit.cover,
        package: package,
        placeholderBuilder: (context) {
          return _placeHoldWidget();
        },
      );
    }
    assert(false);
    return Container();
  }

  ///占位图片
  Widget _placeHoldWidget() {
    if (placeHoldWidget != null) {
      return placeHoldWidget;
    }
    if (placeHoldUrl != null && placeHoldUrl.isNotEmpty) {
      return imageFromAsset(
        placeHoldUrl,
        width: width,
        height: height,
        fit: fit ?? BoxFit.cover,
        package: placeHoldPackage,
      );
    }
    return Container();
  }

  ///构建非svg资源
  Widget _buildNotSvgWidget() {
    ///网络资源
    if (_resourceType == ResourceType.net && imageUrl != null && imageUrl.isNotEmpty) {
      return CachedNetworkImage(
        imageUrl: imageUrl,
        width: width,
        height: height,
        fit: fit ?? BoxFit.cover,
        fadeInDuration: loadingAnimation ? Duration(milliseconds: 500) : Duration(),
        fadeOutDuration: Duration(),
        placeholder: (context, String url) {
          return _placeHoldWidget();
        },
        errorWidget: (context, String url, error) {
          return _placeHoldWidget();
        },
      );
    }

    if (_resourceType == ResourceType.file) {
      return Image.file(
        File(imageUrl != null && imageUrl.isNotEmpty ? imageUrl : placeHoldUrl ?? ''),
        fit: fit ?? BoxFit.cover,
        width: width,
        height: height,
        color: color,
        frameBuilder: loadingAnimation
            ? (context, child, frame, wasSynchronouslyLoaded) {
                if (wasSynchronouslyLoaded) {
                  return child;
                }

                ///图片加载动画
                return loadingAnimation
                    ? AnimatedSwitcher(
                        duration: const Duration(milliseconds: 500),
                        child: frame != null ? child : _placeHoldWidget(),
                      )
                    : _placeHoldWidget();
              }
            : null,
      );
    }

    if (_resourceType == ResourceType.asset) {
      ///本地资源
      return imageFromAsset(
        imageUrl != null && imageUrl.isNotEmpty ? imageUrl : placeHoldUrl ?? '',
        fit: fit ?? BoxFit.cover,
        width: width,
        height: height,
        color: color,
        package: package,
        frameBuilder: loadingAnimation
            ? (context, child, frame, wasSynchronouslyLoaded) {
                if (wasSynchronouslyLoaded) {
                  return child;
                }

                ///图片加载动画
                return loadingAnimation
                    ? AnimatedSwitcher(
                        duration: const Duration(milliseconds: 500),
                        child: frame != null ? child : _placeHoldWidget(),
                      )
                    : _placeHoldWidget();
              }
            : null,
      );
    }
    return _placeHoldWidget();
  }

  @override
  Widget build(BuildContext context) {
    if (placeHoldUrl != null && placeHoldUrl.length > 1) {
      ///仅支持asset中的资源
      assert(!isAssetResource(placeHoldUrl), '请使用 placeHoldWidget 自定义内容，placeHoldUrl 仅支持asset资源');
    }
    Widget childContent;
    if (imageUrl != null && imageUrl.isNotEmpty && path.extension(imageUrl) == '.svg') {
      childContent = _buildSvgWidget();
    } else {
      childContent = _buildNotSvgWidget();
    }

    return borderRadius != null
        ? ClipRRect(
            borderRadius: borderRadius,
            child: childContent,
          )
        : childContent;
  }
}
